/* eslint-disable */
import axios from 'axios'
import store from '@/vuex'
import router from '@/router'
import { Notify, Dialog } from 'vant';

// create an axios instance
const service = axios.create({
  baseURL: '/api/', // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 20000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  (config) => {
    // do something before request is sent

    if (store.getters.currentUser) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['Authorization'] = localStorage.getItem('appAuthorization')
      config.headers['warehouseId'] = localStorage.getItem('warehouseId')
    }
    return config
  },
  (error) => {
    // do something with request error
    console.log(error) // for debug
    global.utils.loadHide()
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  (response) => {
    global.utils.loadHide()
    const res = response.data

    if (!res.success) {
      //扫描类型的，失败后，给提示音乐
      if (
        (response.config && response.config.data && JSON.parse(response.config.data).isScan)  //post,参数为{param}
        || (response.config && response.config.params && response.config.params.isScan)  //post,参数为param
        || (response.config && response.config.url && response.config.url.indexOf('isScan') != -1)  //get
      ) {
        window.scanError()
        console.clear()
        console.info('ajaxerroeajaxerroeajaxerroeajaxerroeajaxerroeajaxerroeajaxerroeajaxerroeajaxerroeajaxerroeajaxerroeajaxerroe')
      }

      Notify({
        type: 'warning',
        message: res.msg.replace(/<br>/g,"\n") ,
        duration: 3 * 1000
      });
    }

    if (res && res.msg) res.msg = res.msg.replace(/<br>/g,"\n")

    return res
    // return Promise.reject(new Error(res.msg || 'Error'))
  },
  (error) => {
    console.log(`onRejected-err${error}`) // for debug
    global.utils.loadHide()
    let response = error?error.response:null
    let status = response?response.status:null
    let data = response?response.data:null
    let msg='未知异常'
    if(data && data.needLogin){
      try {
        Dialog.close()
      }catch (e) {
      }
      Dialog.alert({
        title: '系统提示',
        message: '会话超时，请重新登录!',
      }).then(() => {
        router.push('/login', () => {
        })
      });

      return Promise.reject(error)
    }

    if(!status){
      msg= '网络连接异常，请检查本地网络是否连接'
    }else if(status == 401){ //登录超时
      if(response.data.msg){
        msg= '登录超时，请重新登录'
        try {
          Dialog.close()
        }catch (e) {
        }

        Dialog.alert({
          title: '系统提示',
          message: '会话超时，请重新登录!',
        }).then(() => {
          router.push('/login', () => {
          })
        });
        return Promise.reject(error)
      }else if(response.data.message){
        msg= response.data.message
        if(msg.indexOf('服务器异常') == -1) msg='服务器异常，原因:'+msg
      }else if(typeof(response.data) == 'string'  && response.data.indexOf('Proxy error') != -1){
        msg= '服务器暂时无法访问，请稍候重试'
      }
    }else if(status == 500){
      if(response.data.msg){
        msg= response.data.msg
      }else if(response.data.message){
        msg= response.data.message
        if(msg.indexOf('服务器异常') == -1) msg='服务器异常，原因:'+msg
      }else if(typeof(response.data) == 'string'  && response.data.indexOf('Proxy error') != -1){
        msg= '服务器暂时无法访问，请稍候重试'
      }
    }else if(status == 502){
      msg= '代理服务器暂时不可以使用，请稍候重试'
    }

    //扫描类型的，失败后，给提示音乐
    if (
      (response.config && response.config.data && JSON.parse(response.config.data).isScan)  //post,参数为{param}
      || (response.config && response.config.params && response.config.params.isScan)  //post,参数为param
      || (response.config && response.config.url && response.config.url.indexOf('isScan') != -1)  //get
    ) {
      window.scanError()
      console.clear()
      console.info('ajaxerroeajaxerroeajaxerroeajaxerroeajaxerroeajaxerroeajaxerroeajaxerroeajaxerroeajaxerroeajaxerroeajaxerroe')
    }

    Notify({
      type: 'warning',
      message: msg.replace(/<br>/g,"\n"),
      duration: 3 * 1000
    });
    return Promise.reject(error)
  }
)

export default service
